package com.dmzapp.cashoffer.util;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.PackageInfo;

import com.dmzapp.cashoffer.vo.AppInfo;
import com.dmzapp.cashoffer.vo.AppSearchResult;
import com.dmzapp.cashoffer.vo.IncomeRecord;
import com.dmzapp.cashoffer.vo.OutRecord;
import com.dmzapp.cashoffer.vo.UserInResponse;
import com.dmzapp.cashoffer.vo.UserOutResponse;

public class JsonUtil {

    public static UserOutResponse parseUserOutcomeJson(String jsonStr){
        UserOutResponse result = new UserOutResponse();
        
        try {
            JSONObject response = new JSONObject(jsonStr);
            JSONArray inArray = response.getJSONArray("outlist");
            List<OutRecord> inList = new ArrayList<OutRecord>();
            for (int i = 0; i < inArray.length(); i++) {
                JSONObject jsonoutcome = inArray.getJSONObject(i);
                if (jsonoutcome == null) {
                    continue;
                }
                OutRecord record = new OutRecord();
                record.setAmount(jsonoutcome.getString("amount"));
                record.setCreate_time(jsonoutcome.getLong("create_time"));
                record.setTarget(jsonoutcome.getString("target"));
                record.setType(jsonoutcome.getString("type"));
                record.setStatus(jsonoutcome.getString("status"));
                inList.add(record);
            }
            result.setTotalListSize(response.getInt("listSize"));
            result.setOutList(inList);
            result.setTotal(response.getString("amount"));
            result.setRest(response.getString("rest"));
            TimeCounter.getInstance().updateServerTime(response.getLong("server_time"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return result;
    }
    
    public static UserInResponse parseUserIncomeJson(String jsonStr) {
        UserInResponse result = new UserInResponse();
        try {
            JSONObject response = new JSONObject(jsonStr);
            JSONArray inArray = response.getJSONArray("incomelist");
            List<IncomeRecord> inList = new ArrayList<IncomeRecord>();
            for (int i = 0; i < inArray.length(); i++) {
                JSONObject jsonincome = inArray.getJSONObject(i);
                if (jsonincome == null) {
                    continue;
                }
                IncomeRecord record = new IncomeRecord(jsonincome.getInt("serviceid"), 
                        jsonincome.getString("packagename"), jsonincome.getString("income"), jsonincome.getLong("create_time"));
                inList.add(record);
            }
            result.setInList(inList);
            result.setTotalListSize(response.getInt("listSize"));
            result.setTotal(response.getString("amount"));
            result.setRest(response.getString("rest"));
            TimeCounter.getInstance().updateServerTime(response.getLong("server_time"));
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return result;
    }
    
    public static AppSearchResult parseJson(Context context, String jsonStr){
        
        AppSearchResult result = new AppSearchResult();
        
        try {
            JSONObject json = new JSONObject(jsonStr);
            
            JSONObject env = json.getJSONObject("dmzenv");
            
            int total = json.getInt("listSize"); 
            
            JSONArray appList = json.getJSONArray("applist");
            TimeCounter.getInstance().updateServerTime(json.getLong("server_time"));
            
            List<AppInfo> appInfoList = new ArrayList<AppInfo>();
            List<PackageInfo> packageList = context.getPackageManager().getInstalledPackages(0);
            for (int i = 0; i < appList.length(); i++) {
                JSONObject jsonapp = appList.getJSONObject(i);
                if (jsonapp == null) {
                    continue;
                }
                AppInfo appinfo = new AppInfo();
                appinfo.setAppid(jsonapp.getInt("id"));
                appinfo.setApksize(jsonapp.getLong("apk_size"));
                appinfo.setAppName(jsonapp.getString("appname"));
                appinfo.setDescription(jsonapp.getString("description"));
                appinfo.setDownloadFee(jsonapp.getDouble("downloadFee"));
                appinfo.setDownloadURL(env.getString("apkServerpath") + jsonapp.getString("packagename") + ".apk");
                appinfo.setForwardFee(jsonapp.getDouble("forwardFee"));
                appinfo.setIconPath(Constant.ICON_PATH + jsonapp.getString("packagename") + ".png");
                appinfo.setIconServerPath(env.getString("iconServerpath") + jsonapp.getString("packagename") + ".png");
                appinfo.setLongtimeuserFee(jsonapp.getDouble("longtimeuserFee"));
                appinfo.setPackagename(jsonapp.getString("packagename"));
                appinfo.setRateFee(jsonapp.getDouble("rateFee"));
                appinfo.setEffect_running_time(jsonapp.getInt("effect_running_time"));
                appinfo.setMax_times(jsonapp.getInt("max_times"));
                appinfo.setDuration(jsonapp.getInt("duration"));
                appinfo.setPic_number(jsonapp.getInt("pic_number"));
                appinfo.setActive_time(jsonapp.getInt("active_time"));
                appinfo.setCustom_desc(jsonapp.getString("custom_desc"));
                String activeTerm = jsonapp.getString("active_term").replace('[', '<').replace(']', '>')
                        .replace("%gold%", Constant.moneysizeFormat.format(jsonapp.getDouble("downloadFee") * 100)).replace("%time%", jsonapp.getString("active_time"));
                
                appinfo.setActive_term(activeTerm);
                if (AppManager.isAppInstalled(context, jsonapp.getString("packagename"), packageList)) {
                    appinfo.setIntalled(true);
                } else {
                    appinfo.setIntalled(false);
                }
                
                if (jsonapp.getInt("custom_active") == 0) {
                    appinfo.setCustom_active(false);
                } else {
                    appinfo.setCustom_active(true);
                }
                appInfoList.add(appinfo);
            }
            
            result.setResultList(appInfoList);
            result.setTotal(total);
            
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return result;
    }
}
